#! /usr/bin/env python
# -*- coding: utf8 -*-

# Alexandre Coster <acoster@rhrk.uni-kl.de>
# AG DBIS - Technische Universität Kaiserslautern

import sys
import random

if sys.version_info[:2] == (2, 5):
    from xml.etree import cElementTree as et
else:
    import cElementTree as et

# Project imports
import conf

class ShakenXML(object):
    def __init__(self, config_file, xml_file, outfile):
        self.__conf  = conf.config(config_file)
        self.__fname = xml_file
        self.__tree  = et.parse(xml_file)

        self.__transforms = self.__conf.transformations
        self.__algorithms = self.__conf.algorithms
        self.__probDistr  = self.__conf.probDistr

        if outfile == None:
            self.__outfile = None
        else:
            if outfile in ["stdout", "stderr"]:
                self.__outfile = getattr(sys, outfile)
            else:
                self.__outfile = open(outfile, "w")

    def run(self, fnames = []):
        origRoot = self.__tree.getroot()
        results  = []

        nodes   = origRoot.findall(".//%s" % (self.__conf.root,))
        if origRoot.tag == self.__conf.root:
            nodes.append(origRoot)

        if len(fnames) > 1:
            results = self.__transforms[self.__conf.root](nodes = nodes, resultAmmount = len(fnames), addIDs=self.__conf.addIDs)
        else:
            results = self.__transforms[self.__conf.root](nodes = nodes, resultAmmount = len(fnames), addIDs=self.__conf.addIDs,
                                                          outFile = self.__outfile)

        if self.__outfile not in (sys.stderr, sys.stdout, None):
            self.__outfile.close()

        tuplas  = [(results[i], fnames[i]) for i in range(len(fnames))]

        if self.__conf.shuffle:
            for i in results:
                random.shuffle(i)

        if self.__conf.addIDs:
            fp = file("%s-withIDs.xml" % (self.__fname[:-4],), 'w')
            self.__tree.write(fp)
            fp.close()

        for i in tuplas:
            newRoot = et.Element(origRoot.tag)
            newTree = et.ElementTree(newRoot)

            for j in i[0]:
                newRoot.append(j)

            newTree.write(i[1])
